package com.fzu.mmdbproxyframework.multitask;


import java.sql.SQLException;

import org.springframework.stereotype.Service;

import com.fzu.mmdbproxyframework.mmdb.h2.H2DB;
import com.fzu.mmdbproxyframework.model.DBInterf;
import com.fzu.mmdbproxyframework.model.DataNode;
import com.fzu.mmdbproxyframework.model.MMDataNodeCluster;
import com.fzu.mmdbproxyframework.model.MysqlDB;
import com.fzu.mmdbproxyframework.model.Table;



@Service
public class MMDBFullDumpTask extends ScheduledTask{
	private static int count = 0; 
	public MMDataNodeCluster cluster;

	public MMDBFullDumpTask(MMDataNodeCluster cluster) {
		this.cluster=cluster;
	}
	@Override
	public void doTask() {
		System.out.println("ClockingFullDumpTask");
		count = count +1;
    	System.out.println("尝试第"+ count +"次全量同步更新");
    	try {
    		fullUpdateTable();
			
			System.out.println("第"+ count +"次全量同步更新完成");
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("第"+ count +"次全量同步更新失败");
		}
		
		System.out.println("ClockingFullDumpTask");
	}
	@Override
	public long getDelay(){
		return cluster.getConfigContext().getKeepaliveTime();
	}
	@Override
	public void setStop(boolean stop) {
		super.stop = stop;
	}
	
	
	//全量表数据同步   清空表数据  再重新导入数据
	public  void fullUpdateTable() throws SQLException{
		for(DataNode mmdatanode : cluster.getClusterContext().getMMDataNodeList()){
			if(mmdatanode.isRunning()){
				H2DB h2db = (H2DB)mmdatanode.getDb();
				h2db.TruncateTable();//清空mmdb中的表数据
				if(cluster.getClusterContext().getSourceDBNodeList().size() == 1){
					for(DBInterf db:cluster.getClusterContext().getSourceDBNodeList()){
						MysqlDB sourceMysqlDB = (MysqlDB) db;
						for(Table table : h2db.getTableList()){
							sourceMysqlDB.create_insertSqlByTable(table);
						}
					}
				}
			}
			
		}
		
		
	}
}

